﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using GWEB.WebBase.Data;
using GWEB.WebBase.Entity;
using GWEB.WebBase.Utility;
using GWEB.WebFrame.Public;

namespace GWEB.WebFrame.Models
{
    public class Customer
    {        
        public PageInfo Init()
        {
            PageInfo pg = new PageInfo();
            HttpSessionState session =System.Web.HttpContext.Current.Session;
            pg.dict = BasePage.getDict(session);
            pg.Type = "Customer";
            pg.ConditionColumn = 2;
            pg.Title = "客户管理";
            pg.AddText = "客户增加";
            pg.EditText = "客户修改";          
            pg.LocateText = "客户信息查询";
            pg.SMenuId = "KH";
            pg.FileUrl = "";
            pg.Condition = "";
            pg.TableName = "cu_Customers";
            pg.KeyFieldName = "id";
            pg.PopEditHeight = 500;
            pg.PopEditWidth = 700;
            pg.Sop = BasePage.Grant(session, pg.SMenuId);

            pg.Sop.ADD = false; pg.Sop.EDIT = false;pg.Sop.DEL = false;
            
            //0，新增未分配，1，已分配未领取，2、已领取未跟进，3，已跟进，4已预约，5已交定金，6，已签合同,7历史客户，8淘汰 9退订金 10退合同
            Dictionary<String, String> tab = new Dictionary<string, string>();

            if (BasePage.Grant(session,pg.SMenuId, "ADD"))
                pg.Button.Add("<li onclick=\"ShowModalUrl('popEdit', '../Customer/Create?id=-1', '创建', '', '700', '500')\" class='layui-btn layui-btn-normal'><i class='layui-icon layui-icon-add-1'></i>创建</li>");
            if (BasePage.Grant(session, pg.SMenuId, "EDIT"))
                pg.Button.Add("<li onclick=\"ShowModalUrl('popEdit', '../Customer/Import', '导入', '', '', '')\" class='layui-btn layui-btn-normal'><i class='iconfont icon-daoru'></i>导入</li>");
            if (BasePage.Grant(session, pg.SMenuId, "ADD")|| BasePage.Grant(session, pg.SMenuId, "EDIT")|| BasePage.Grant(session, pg.SMenuId, "FP"))
                tab.Add("0", "待分配");
            if (BasePage.Grant(session, pg.SMenuId, "FP"))
            {
                pg.Button.Add("<li onclick=\"GetSelectIds();if(Ids=='') layui.layer.msg('请选择分配记录！'); else ShowModalUrl('popEdit', '../Customer/Distribution?Ids='+Ids+'&KeyCodes='+KeyCodes, '分配', '','700', '500')\" class='layui-btn layui-btn-normal'><i class='iconfont icon-icon-p_gongyingshangfenpei'></i>分配</li>");
                tab.Add("20", "已分配");
            }
            if (BasePage.Grant(session, pg.SMenuId, "LQ"))
            {
                pg.Button.Add("<li onclick=\"GetSelectIds();if(Ids=='') layui.layer.msg('请选择待领取记录！'); else layer.confirm('您确定要领取吗？', function (index) {layer.close(index);Do('../Customer/Receive',{Ids:Ids,KeyCodes:KeyCodes},true) });\" class='layui-btn layui-btn-normal'><i class='iconfont icon-lingqukehu'></i>领取</li>");
                tab.Add("1", "待领取");
            }
            if (BasePage.Grant(session, pg.SMenuId, "GJ"))
            {
                //pg.Button.Add("<li onclick=\"if(KeyFocusId==''||TabIndex!=2) layui.layer.msg('您没有选择一条待跟进记录！'); else ShowModalUrl('popEdit', '../Customer/Followup?id=-1&Ids='+KeyFocusId+'&KeyCodes='+ GetKeyCode(KeyFocusId), '跟进', '', '', '')\" class='layui-btn layui-btn-normal'><i class='iconfont icon-mingdangenjin'></i>跟进</li>");
                pg.Button.Add("<li onclick=\"parent.AddWin('../Main/ManagerLay?type=FollowupList', '客户跟进')\" class='layui-btn layui-btn-normal'><i class='iconfont icon-mingdangenjin'></i>跟进</li>");
                tab.Add("2", "待跟进");
            }
            if (BasePage.Grant(session, pg.SMenuId, "QY"))
            {                
                //pg.Button.Add("<li onclick=\"if(KeyFocusId==''||TabIndex!=5) layui.layer.msg('您没有选择一条待签约记录！'); else ShowModalUrl('popEdit', '../Contract/ContractList?id=-1&Ids='+KeyFocusId+'&KeyCodes='+ GetKeyCode(KeyFocusId), '签约', '', '', '')\" class='layui-btn layui-btn-normal'><i class='iconfont icon-qianyue'></i>签约</li>");
                pg.Button.Add("<li onclick=\"parent.AddWin('../Main/ManagerLay?type=ContractCustomertList', '客户签约')\" class='layui-btn layui-btn-normal'><i class='iconfont icon-qianyue'></i>签约</li>");
                tab.Add("5", "待签约");
            }

            tab.Add("4", "今日预约");
            tab.Add("60", "新会员");
            tab.Add("61", "老会员");
            tab.Add("7", "历史客户");
            tab.Add("21", "合同审核未通过");

            String day = pg.dict.GetValue2("D02", "1");           
            DataRow drUser = BasePage.GetUser(session);
            String dataCond = GrantData.GetDataCond(BasePage.bd, pg.Type, drUser, null);
            String sqlCount = String.Format(@"select custState,count(*) count from
(
	select 
		case
            when custState=6 then 
		    (
			    case when datediff(d,createDate,t2.contractDate)<={0} then 60 
                    when datediff(d,createDate,t2.contractDate)>{0} then 61 
                end
		    )	
            when custState=4 then
            (
               case when convert(varchar(10),getdate(),120)=convert(varchar(10),NextMakeDate,120) then 4 else -1 end
            )
		    else custState end custState
	from cu_Customers t1
	left join (
		select cid,min(createDate) contractDate from cu_Contract group by cid
	) t2 on t1.id=t2.cid
	where 1=1 {1}
) t
group by custState
union
select 20,sum(case when custState in (1,2,3) then 1 else 0 end) from  cu_Customers where 1=1 {1}
union
select 21,count(*) from cu_Customers t1,cu_Contract t2 where t1.id=t2.cid and t2.state=3 {1}", day,dataCond);

            DataView dv=BasePage.bd.ExecuteTable(sqlCount).DefaultView;
            foreach (var dr in tab) {
                int count=0;
                String value = "";
                dv.RowFilter = "custState="+dr.Key;
                if (dv.Count == 1)
                    count = int.Parse(dv[0]["count"].ToString());
                if (count > 99)
                    value = "+99";
                else if (count > 0)
                    value = count.ToString();
                if (count > 0)
                    value = "<span class='layui-badge'>" + value + "</span>";
                pg.Tab.Add(dr.Value+value, "KeyFocusId='';TabIndex=" + dr.Key+";LocatePara='';DataPageUrl='../Main/DataPageLay?type=Customer&state="+dr.Key+"';GoPage(1);");
            }
            
            HttpRequest request = System.Web.HttpContext.Current.Request;
            String state = Fun.cString(request["state"]);
            String condition = "";
            if (state == "20")
                condition = String.Format(" and custState in (1,2,3)");//已分配列=待领取+待跟进+已跟进
            else if (state=="60")
                condition = String.Format(" and custState=6 and datediff(d,t1.createDate,t3.contractDate)<={0}", day);
            else if(state=="61")
                condition = String.Format(" and custState=6 and datediff(d,t1.createDate,t3.contractDate)>{0}", day);
            else if (state == "4")
                condition = String.Format(" and custState=4 and convert(varchar(10),getdate(),120)=convert(varchar(10),NextMakeDate,120) ");
            else
                condition = String.Format(" and custState={0} ", state);

            //按钮
            String button = "";
            switch (state)
            {
                case "0":
                    if (BasePage.Grant(session, pg.SMenuId, "FP"))
                        button += "<a href=\"javascript: layer.confirm('您确定要将客户改为历史状态吗？', function (index) {layer.close(index);Do('../Customer/Distribution/History',{ id:[id],keyCode: GetKeyCode('[id]')},true);})\"  class='layui-btn layui-btn-xs layui-btn-normal '>历史</a>";
                    break;
                case "1":
                    if (BasePage.Grant(session, pg.SMenuId, "LQ"))
                        button += "<a href=\"javascript: layer.confirm('您确定要退回吗？', function (index) {layer.close(index);Do('../Customer/Receive/Return',{ id:[id],keyCode: GetKeyCode('[id]')},true);})\"  class='layui-btn layui-btn-xs'>退回</a>";
                    break;
                case "2":
                    if (BasePage.Grant(session, pg.SMenuId, "GJ"))
                        button += "<a href=\"javascript:ShowModalUrl('popEdit', '../Customer/Followup?id=-1&Ids=[id]&KeyCodes='+ GetKeyCode('[id]'), '跟进', '', '', '') \"  class='layui-btn layui-btn-xs'>跟进</a>";
                    break;
                case "5":
                    if(BasePage.Grant(session, pg.SMenuId, "QY"))
                    button += "<a href=\"javascript:ShowModalUrl('popEdit', '../Contract/ContractList?id=-1&cid=[id]&KeyCodes='+ GetKeyCode('[id]'), '签约', '', '', '') \"  class='layui-btn layui-btn-xs'>签约</a>";
                    break;
                default:                    
                    break;
            }
            button += "<a href =\"javascript:ShowModalUrl('popEdit', '../Customer/CustomerMore?id=[id]&keyCode='+GetKeyCode([id]), '详情', '', '', '')\" class='layui-btn layui-btn-primary layui-btn-xs'>详情</a><a href=\"javascript:ShowModalUrl('popEdit', '../Customer/CustomerEdit?id=[id]&keyCode='+GetKeyCode([id]), '补充', '', 700, 500)\" class='layui-btn layui-btn-primary layui-btn-xs'>补充</a>";
           
            ColumnInfo cl;
            cl = new ColumnInfo(); cl.DataType = Tag.Text; cl.FieldName = "custName"; cl.HeadText = "宝宝姓名"; cl.IsCondition = true; cl.ConditionPosition = 1; pg.AddColumn(cl);
            if (state == "21")
            {
                pg.Sql = String.Format(@"
select* from (
select 
	t1.*,
	t2.contractNumber,t2.SetmealName,ltrim(t2.ContractPrice)+'/'+ltrim(t2.DisPrice) as price,t2.state,t2.AuditingDate,t2.Remark,
	t3.dname as stateCn
from cu_Customers t1
inner join cu_Contract t2 on t1.id=t2.cid and t2.state=3
left join tb_sys_dictionary t3 on t2.state=t3.did and t3.typeid='D07'
) cu_Customers
where 1=1");
                cl = new ColumnInfo(); cl.DataType = Tag.Text; cl.FieldName = "contractNumber"; cl.HeadText = "合同编号"; cl.IsCondition = true; pg.AddColumn(cl);
                cl = new ColumnInfo(); cl.DataType = Tag.Text; cl.FieldName = "SetmealName"; cl.HeadText = "套餐名称"; cl.IsCondition = true; pg.AddColumn(cl);
                cl = new ColumnInfo(); cl.DataType = Tag.Text; cl.FieldName = "price"; cl.HeadText = "价格/实收"; cl.IsCondition = true; cl.ConditionPosition = 1; pg.AddColumn(cl);
                cl = new ColumnInfo(); cl.DataType = Tag.DateTime; cl.FieldName = "AuditingDate"; cl.HeadText = "审核时间"; cl.IsCondition = true; pg.AddColumn(cl);
                cl = new ColumnInfo(); cl.DataType = Tag.Text; cl.FieldName = "linkName"; cl.HeadText = "家长姓名"; cl.IsCondition = true; cl.ConditionPosition = 1; pg.AddColumn(cl);
                cl = new ColumnInfo(); cl.DataType = Tag.Text; cl.FieldName = "custTel"; cl.HeadText = "联系电话"; cl.IsCondition = true; cl.ConditionPosition = 1; pg.AddColumn(cl);
                cl = new ColumnInfo(); cl.DataType = Tag.Text; cl.FieldName = "Remark"; cl.HeadText = "合同备注"; cl.IsCondition = true; pg.AddColumn(cl);
                cl = new ColumnInfo(); cl.DataType = Tag.Text; cl.FieldName = "state"; cl.HeadText = "审核结果"; cl.IsCondition = true; cl.Visible = false; cl.DictTypeID = "D07"; pg.AddColumn(cl);
                cl = new ColumnInfo(); cl.DataType = Tag.Text; cl.FieldName = "stateCn"; cl.HeadText = "审核结果"; pg.AddColumn(cl);
            }
            else {//
                pg.Sql = String.Format(@"
select * from (
    select t1.*,
        datediff(m,BirdDate,getdate()) custMonth,		
        t2.dname custStateCn,
		datediff(hh,getdate(),t4.createDate)+ReceInterval as receHour,
		FollowupCount,
		'' link
    from cu_Customers t1
    left join tb_sys_dictionary t2 on t1.CustState = t2.did and t2.typeid = 'D01'
    left join (
	    select cid,min(createDate) contractDate from cu_Contract group by cid
    ) t3 on t1.id=t3.cid
	left join (
		select ROW_NUMBER() over(partition by cid order by id desc) rn,cid,createDate,ReceInterval from cu_Cus_Distribution
	) t4 on t4.rn=1 and t4.cid=t1.id
	left join (
		select cid,count(*) FollowupCount from cu_Cus_followup group by cid
	) t5 on t5.cid=t1.id
    where 1=1 {0}
) cu_Customers where 1=1", condition);
                cl = new ColumnInfo(); cl.DataType = Tag.Text; cl.FieldName = "childName"; cl.HeadText = "宝宝小名"; cl.IsCondition = true; pg.AddColumn(cl);
                cl = new ColumnInfo(); cl.DataType = Tag.Decimal; cl.FieldName = "custMonth"; cl.HeadText = "月龄"; cl.IsCondition = true; pg.AddColumn(cl);
                cl = new ColumnInfo(); cl.DataType = Tag.Text; cl.FieldName = "linkName"; cl.HeadText = "家长姓名"; cl.IsCondition = true; cl.ConditionPosition = 1; pg.AddColumn(cl);
                cl = new ColumnInfo(); cl.DataType = Tag.Text; cl.FieldName = "custTel"; cl.HeadText = "联系电话"; cl.IsCondition = true; cl.ConditionPosition = 1; pg.AddColumn(cl);

                switch (state)
                {
                    case "0"://待分配
                        cl = new ColumnInfo(); cl.DataType = Tag.DateTime; cl.FieldName = "CreateDate"; cl.HeadText = "导入时间"; cl.IsCondition = true; pg.AddColumn(cl);
                        break;
                    case "1"://待领取
                        cl = new ColumnInfo(); cl.DataType = Tag.DateTime; cl.FieldName = "receHour"; cl.HeadText = "待领取倒计时"; cl.IsCondition = true; pg.AddColumn(cl);
                        break;
                    case "2"://待跟进
                        cl = new ColumnInfo(); cl.DataType = Tag.Decimal; cl.FieldName = "FollowupCount"; cl.HeadText = "跟进次数"; cl.IsCondition = true; pg.AddColumn(cl);
                        cl = new ColumnInfo(); cl.DataType = Tag.DateTime; cl.FieldName = "NextMakeDate"; cl.HeadText = "下次联系时间"; cl.IsCondition = true; pg.AddColumn(cl);
                        break;
                    case "5"://待签约
                        cl = new ColumnInfo(); cl.DataType = Tag.DateTime; cl.FieldName = "ContractDate"; cl.HeadText = "签约日期"; cl.IsCondition = true; pg.AddColumn(cl);
                        break;
                    default:
                        cl = new ColumnInfo(); cl.DataType = Tag.DateTime; cl.FieldName = "latelyFoupDate"; cl.HeadText = "最近跟进时间"; cl.IsCondition = true; pg.AddColumn(cl);
                        break;
                }
                cl = new ColumnInfo(); cl.DataType = Tag.Text; cl.FieldName = "custFromId"; cl.HeadText = "渠道来源"; cl.IsCondition = true; cl.Visible = false; cl.DictTypeID = "D03"; pg.AddColumn(cl);
                cl = new ColumnInfo(); cl.DataType = Tag.Text; cl.FieldName = "custFrom"; cl.HeadText = "渠道来源"; pg.AddColumn(cl);
                cl = new ColumnInfo(); cl.DataType = Tag.Text; cl.FieldName = "custRemark"; cl.HeadText = "备注"; cl.IsCondition = true; pg.AddColumn(cl);
                cl = new ColumnInfo(); cl.DataType = Tag.Text; cl.FieldName = "custState"; cl.HeadText = "状态"; cl.IsCondition = true; cl.Visible = false; cl.DictTypeID = "D01"; pg.AddColumn(cl);
                cl = new ColumnInfo(); cl.DataType = Tag.Text; cl.FieldName = "custStateCn"; cl.HeadText = "状态"; pg.AddColumn(cl);
                if (!button.Equals(""))
                { cl = new ColumnInfo(); cl.DataType = Tag.Text; cl.FieldName = "link"; cl.HeadText = "操作"; cl.IsSort = false; cl.Script = button; pg.AddColumn(cl); }
            }
            return pg;
        }
    }
}